using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Windows.Controls;

namespace DocumentCreationSystem.Views.Dialogs;

/// <summary>
/// AI工具参数输入对话框
/// </summary>
public partial class AIToolParameterDialog : Window
{
    private readonly string _toolId;
    private readonly List<AIToolParameter> _parameters;
    private readonly Dictionary<string, Control> _parameterControls;
    private readonly IAIToolsService _aiToolsService;

    public AIToolParameterDialog(string toolId, List<AIToolParameter> parameters)
    {
        InitializeComponent();
        
        _toolId = toolId;
        _parameters = parameters;
        _parameterControls = new Dictionary<string, Control>();
        
        _aiToolsService = App.ServiceProvider?.GetService<IAIToolsService>() 
            ?? throw new InvalidOperationException("无法获取AI工具服务");

        InitializeDialog();
        CreateParameterControls();
    }

    /// <summary>
    /// 初始化对话框
    /// </summary>
    private void InitializeDialog()
    {
        ToolNameText.Text = $"工具参数设置 - {_toolId}";
        ToolDescriptionText.Text = $"请设置工具执行所需的 {_parameters.Count} 个参数";
    }

    /// <summary>
    /// 创建参数控件
    /// </summary>
    private void CreateParameterControls()
    {
        foreach (var parameter in _parameters)
        {
            CreateParameterControl(parameter);
        }
    }

    /// <summary>
    /// 创建单个参数控件
    /// </summary>
    private void CreateParameterControl(AIToolParameter parameter)
    {
        // 创建标签
        var labelPanel = new StackPanel { Orientation = Orientation.Horizontal };
        
        var label = new TextBlock
        {
            Text = parameter.DisplayName,
            Style = (Style)FindResource("ParameterLabelStyle")
        };
        labelPanel.Children.Add(label);

        if (parameter.IsRequired)
        {
            var requiredIndicator = new TextBlock
            {
                Style = (Style)FindResource("RequiredIndicatorStyle")
            };
            labelPanel.Children.Add(requiredIndicator);
        }

        ParametersContainer.Children.Add(labelPanel);

        // 创建描述
        if (!string.IsNullOrEmpty(parameter.Description))
        {
            var description = new TextBlock
            {
                Text = parameter.Description,
                FontSize = 11,
                Foreground = System.Windows.Media.Brushes.Gray,
                Margin = new Thickness(0, 0, 0, 5),
                TextWrapping = TextWrapping.Wrap
            };
            ParametersContainer.Children.Add(description);
        }

        // 根据参数类型创建输入控件
        Control inputControl = parameter.Type.ToLower() switch
        {
            "boolean" or "bool" => CreateBooleanControl(parameter),
            "integer" or "int" => CreateIntegerControl(parameter),
            "array" => CreateArrayControl(parameter),
            "text" => CreateTextAreaControl(parameter),
            _ => CreateStringControl(parameter)
        };

        inputControl.Style = (Style)FindResource("ParameterInputStyle");
        _parameterControls[parameter.Name] = inputControl;
        ParametersContainer.Children.Add(inputControl);
    }

    /// <summary>
    /// 创建布尔值控件
    /// </summary>
    private Control CreateBooleanControl(AIToolParameter parameter)
    {
        var checkBox = new CheckBox
        {
            Content = parameter.DisplayName,
            IsChecked = parameter.DefaultValue != null && Convert.ToBoolean(parameter.DefaultValue)
        };
        return checkBox;
    }

    /// <summary>
    /// 创建整数控件
    /// </summary>
    private Control CreateIntegerControl(AIToolParameter parameter)
    {
        var textBox = new TextBox();
        
        if (parameter.DefaultValue != null)
        {
            textBox.Text = parameter.DefaultValue.ToString();
        }

        return textBox;
    }

    /// <summary>
    /// 创建数组控件
    /// </summary>
    private Control CreateArrayControl(AIToolParameter parameter)
    {
        var textBox = new TextBox
        {
            Height = 80,
            TextWrapping = TextWrapping.Wrap,
            AcceptsReturn = true,
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto
        };

        // 添加提示文本
        textBox.ToolTip = "请输入多个值，每行一个";

        return textBox;
    }

    /// <summary>
    /// 创建文本区域控件
    /// </summary>
    private Control CreateTextAreaControl(AIToolParameter parameter)
    {
        var textBox = new TextBox
        {
            Height = 120,
            TextWrapping = TextWrapping.Wrap,
            AcceptsReturn = true,
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto
        };

        if (parameter.DefaultValue != null)
        {
            textBox.Text = parameter.DefaultValue.ToString();
        }

        return textBox;
    }

    /// <summary>
    /// 创建字符串控件
    /// </summary>
    private Control CreateStringControl(AIToolParameter parameter)
    {
        if (parameter.Options.Any())
        {
            // 创建下拉框
            var comboBox = new ComboBox();
            foreach (var option in parameter.Options)
            {
                comboBox.Items.Add(option);
            }

            if (parameter.DefaultValue != null)
            {
                comboBox.SelectedItem = parameter.DefaultValue.ToString();
            }

            return comboBox;
        }
        else
        {
            // 创建文本框
            var textBox = new TextBox();
            
            if (parameter.DefaultValue != null)
            {
                textBox.Text = parameter.DefaultValue.ToString();
            }

            return textBox;
        }
    }

    /// <summary>
    /// 获取参数值
    /// </summary>
    public Dictionary<string, object> GetParameters()
    {
        var parameters = new Dictionary<string, object>();

        foreach (var parameter in _parameters)
        {
            if (_parameterControls.TryGetValue(parameter.Name, out var control))
            {
                var value = GetControlValue(control, parameter);
                if (value != null)
                {
                    parameters[parameter.Name] = value;
                }
            }
        }

        return parameters;
    }

    /// <summary>
    /// 获取控件值
    /// </summary>
    private object? GetControlValue(Control control, AIToolParameter parameter)
    {
        return control switch
        {
            CheckBox checkBox => checkBox.IsChecked ?? false,
            ComboBox comboBox => comboBox.SelectedItem?.ToString() ?? "",
            TextBox textBox when parameter.Type.ToLower() == "array" => 
                textBox.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries).ToList(),
            TextBox textBox when parameter.Type.ToLower() is "integer" or "int" => 
                int.TryParse(textBox.Text, out var intValue) ? intValue : parameter.DefaultValue,
            TextBox textBox => textBox.Text,
            _ => null
        };
    }

    /// <summary>
    /// 验证参数按钮点击事件
    /// </summary>
    private async void ValidateButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var parameters = GetParameters();
            var validation = await _aiToolsService.ValidateParametersAsync(_toolId, parameters);

            if (validation.IsValid)
            {
                MessageBox.Show("参数验证通过！", "验证成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                var errorMessage = string.Join("\n", validation.Errors);
                var warningMessage = validation.Warnings.Any() ? 
                    "\n\n警告:\n" + string.Join("\n", validation.Warnings) : "";
                
                MessageBox.Show($"参数验证失败:\n{errorMessage}{warningMessage}", 
                    "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"验证参数时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 执行工具按钮点击事件
    /// </summary>
    private async void ExecuteButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var parameters = GetParameters();
            var validation = await _aiToolsService.ValidateParametersAsync(_toolId, parameters);

            if (!validation.IsValid)
            {
                var errorMessage = string.Join("\n", validation.Errors);
                MessageBox.Show($"参数验证失败:\n{errorMessage}", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            DialogResult = true;
            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"准备执行工具时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 取消按钮点击事件
    /// </summary>
    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }
}
